﻿// -----------------------------------------------------------------------
// <copyright file="CacheInvalidationHandler.cs" company="SoftServe">
// handler for work with cache invalidation
// </copyright>
// -----------------------------------------------------------------------
namespace WebServer.BusinessLogic.Handlers
{
    using WebServer.BusinessLogic.Web;
    using WebServer.BusinessLogic.Web.Cache;

    /// <summary>
    /// Handles invalidation of cache requests (such as POST method)
    /// </summary>
    public class CacheInvalidationHandler : Handler
    {
        /// <summary>
        /// Session manager to use within this Handler
        /// </summary>
        private CacheManagerInstance _cacheManager;

        /// <summary>
        /// Configurator to use within this Handler
        /// </summary>
        private Configurator _configurator;

        /// <summary>
        /// Initializes a new instance of the <see cref="CacheInvalidationHandler" /> class.
        /// </summary>
        public CacheInvalidationHandler()
        {
            this._cacheManager = CacheManager.Instance;
            this._configurator = Configurator.Instance;
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="CacheInvalidationHandler" /> class.
        /// </summary>
        /// <param name="cacheManager">fake interface for testing</param>
        /// <param name="configurator">fake configurator for injecting</param>
        public CacheInvalidationHandler(CacheManagerInstance cacheManager, Configurator configurator)
            : this()
        {
            this._cacheManager = cacheManager;
            this._configurator = configurator;
        }

        /// <summary>
        /// Process http request for cache invalidation and always moves to next handler
        /// </summary>
        /// <param name="request">http request</param>
        /// <returns>http response</returns>
        public override Response Handle(Request request)
        {
            if (_configurator.IsCacheEnabled && request.HttpMethod == EnumHttpMethod.POST)
            {
                string cacheKey = request.HttpPath;

                var cacheItem = _cacheManager.GetCachedItem(cacheKey);
                if (cacheItem != null)
                {
                    // got the cache item, let's invalidate it
                    _cacheManager.RemoveItemByKey(cacheKey);
                }
            }
                
            return this.NextHandler.Handle(request);
        }
    }
}
